package com.freecloud.whispered.auth.service.impl;

import cn.hutool.core.date.DateUtil;
import com.freecloud.framework.request.R;
import com.freecloud.framework.service.AbstractBaseService;
import com.freecloud.whispered.auth.entity.SysUserTokenEntity;
import com.freecloud.whispered.auth.oauth2.TokenGenerator;
import com.freecloud.whispered.auth.repository.SysUserTokenDao;
import com.freecloud.whispered.auth.service.SysUserTokenService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author: maomao
 * @Date: 2019-06-20 10:03
 */
@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends AbstractBaseService<SysUserTokenEntity,Long, SysUserTokenDao> implements SysUserTokenService {

    /**
     * 12小时后过期
     */
    private final static int EXPIRE = 60 * 60 * 12 * 1000;

    @Override
    public R createToken(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = DateUtil.date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE);

        //判断是否生成过token
        SysUserTokenEntity tokenEntity = this.queryObject(userId);
        if(tokenEntity == null){
            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            this.save(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            this.save(tokenEntity);
        }

        return R.ok().put("token", token).put("expire", EXPIRE);
    }

    @Override
    public void logout(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        this.save(tokenEntity);
    }
}
